package com.prs.crm.log;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.courser.Util;
import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.sys.Form;
import com.prs.crm.domain.sys.Log;
import com.prs.crm.domain.sys.LogItem;
import com.prs.crm.domain.sys.Module;
import com.prs.crm.service.sys.FormService;
import com.prs.crm.service.sys.LogService;

public class LoggerImpl implements ILogger{
	
	private static final String key = "com.prs.sys.session.log.currentLog";
	
	@Autowired
	private FormService formService;
	
	@Autowired
	private LogService logService;
	
	private Map<String,Form> formRelations;
	
	
	public LoggerImpl()
	{	
	}
	
	private void init()
	{
		formRelations = new HashMap<String,Form>();
		Collection<Form> forms = this.getFormService().getAllForm();
		for (Form form : forms)
		{
			formRelations.put(form.getClassName().trim(), form);
		}
	}
	
	public void setFormService(FormService formService) {
		this.formService = formService;
	}

	public FormService getFormService() {
		return formService;
	}

	public LogService getLogService() {
		return logService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	public void setFormRelations(Map<String,Form> formRelations) {
		this.formRelations = formRelations;
	}

	public Map<String,Form> getFormRelations() {
		if (formRelations==null)
			init();
		return formRelations;
	}

	public void logModule(Module module,Person person,String ip)
	{
		Log log = new Log();
		log.setAccessTime(Util.nowFullTime());
		log.setModule(module);
		log.setOperator(person);
		log.setIp(ip);
		this.getLogService().save(log);
		this.setCurrentLog(log);
	}
	
	public void logOper(Class<?> cls,Object id, int opertype)
	{
		Log log = this.getCurrentLog();
		if (log!=null)
		{
			String className = cls.getName();
			int proxypos = className.indexOf("_$$");
			if (proxypos>0)
				className = className.substring(0,proxypos);
			Form form = this.getFormRelations().get(className);
			if (form!=null)
			{
				LogItem item = new LogItem();
				item.setLog(log);
				item.setForm(form);
				item.setTargetId(id.toString());
				item.setOperTime(Util.nowFullTime());
				item.setType(opertype);
				this.getLogService().saveLogItem(item);
			}
		}
	}
	

	

	private Log getCurrentLog()
	{
		HttpSession session = ServletActionContext.getRequest().getSession();
		Log currentLog = (Log)session.getAttribute(key);
		return currentLog;
	}
	
	private void setCurrentLog(Log log)
	{
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.setAttribute(key, log);
	}
	
}
